package com.lcf.system.manager;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.base.exception.SysException;
import com.lcf.system.dto.role.SysRoleDTO;
import com.lcf.system.entity.SysRole;
import com.lcf.system.entity.SysUserRole;
import com.lcf.system.enums.SysRoleEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 描述：角色
 *
 * @author lcf
 * @since 2025/3/3 13:49
 */
@Component
public class SysRoleManager {
    /**
     * 检查id
     */
    public SysRole checkId(long id) {
        SysRole sysRole = Db.lambdaQuery(SysRole.class).eq(SysRole::getId, id).one();
        if (sysRole == null) {
            throw new SysException("角色不存在");
        }

        return sysRole;
    }

    /**
     * 检查角色是否存在
     */
    public void checkExist(Long id, SysRoleDTO dto) {
        boolean exists = Db.lambdaQuery(SysRole.class)
                .ne(id != null, SysRole::getId, id)
                .and(w -> w.eq(SysRole::getRoleName, dto.getRoleName())
                        .or()
                        .eq(SysRole::getRoleCode, dto.getRoleCode()))
                .exists();

        if (exists) {
            throw new SysException("角色已存在!");
        }
    }

    /**
     * 检查是否至少有一位其他的管理员
     */
    public void checkLastAdmin(long userId, List<SysRole> roleList) {
        if (CollectionUtils.isNotEmpty(roleList)
                && roleList.stream().anyMatch(x -> x.getRoleCode().equals(SysRoleEnum.ADMIN.getCode()))) {
            return;
        }

        SysRole adminRole = Db.lambdaQuery(SysRole.class)
                .eq(SysRole::getRoleCode, SysRoleEnum.ADMIN.getCode())
                .one();

        boolean exists = Db.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getRoleId, adminRole.getId())
                .ne(SysUserRole::getUserId, userId)
                .exists();

        if (!exists) {
            throw new SysException("至少保留一位管理员");
        }
    }

    /**
     * 根据角色id获取用户id
     */
    public List<Long> getUserIdByRoleId(List<Long> roleIdList) {
        if (CollectionUtils.isEmpty(roleIdList)) {
            return Collections.emptyList();
        }

        return Db.lambdaQuery(SysUserRole.class)
                .in(SysUserRole::getRoleId, roleIdList)
                .select(SysUserRole::getUserId)
                .list().stream()
                .map(SysUserRole::getUserId)
                .distinct().toList();
    }
}
